--------------------------------------------------------------------------------
-- Company: 
-- Engineer:
--
-- Create Date:    12:55:27 10/22/05
-- Design Name:    
-- Module Name:    FREdgeDetect - Behavioral
-- Project Name:   
-- Target Device:  
-- Tool versions:  
-- Description:
--
-- Dependencies:
-- 
-- Revision:
-- Revision 0.01 - File Created
-- Additional Comments:
-- 
--------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_ARITH.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

---- Uncomment the following library declaration if instantiating
---- any Xilinx primitives in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity FREdgeDetect is
    Port ( clk : in std_logic;
           Edge : in std_logic;
           FED : out std_logic;
           RED : out std_logic);
end FREdgeDetect;

architecture Behavioral of FREdgeDetect is
	
	type state is(
		stIdleHigh,
		stIdleLow,
		stLowEdge,
		stHighEdge);

	signal stCur : state := stIdleHigh;
	signal stNext : state;
	signal EdgeSync : std_logic_vector(2 downto 0);

begin

	process(clk)
	begin
		if(clk = '0' and clk'event) then
			stCur <= stNext;
		end if;
	end process;

	process(clk)
	begin
		if(clk = '0' and clk'event) then
			EdgeSync(0) <= edge;
			EdgeSync(1) <= EdgeSync(0);
			EdgeSync(2) <= EdgeSync(1);
		end if;
	end process;
	
	process(clk, EdgeSync(2))
	begin
		if(clk = '1' and clk'event) then
			case stCur is
				when stIdleHigh =>
					FED <= '0';
					RED <= '0';
					if(EdgeSync(2) = '0') then
						stNext <= stLowEdge;
					else
						stNext <= stIdleHigh;
					end if;
				when stLowEdge =>
					FED <= '1';
					RED <= '0';
					stNext <= stIdleLow;
				when stIdleLow =>
					FED <= '0';
					RED <= '0';
					if(EdgeSync(2) = '1') then
						stNext <= stHighEdge;
					else
						stNext <= stIdleLow;
					end if;
				when stHighEdge =>
					FED <= '0';
					RED <= '1';
					stNext <= stIdleHigh;
			end case;
		end if;
	end process;								
							
end Behavioral;
